import fs from 'fs';
let dir = "token";
let json;
let updList = [];

fs.open(dir,"a+",function (err,fd) {

    if(err){

        fs.chmod(dir,0x777)
    }
} );

let ConstJsonManager = {

    get(key){

        return  new Promise((resolve, reject) => {


            if(json){

                resolve(json[key]);
                return;
            }

            fs.readFile(dir,(err,data) => {

                if(!data || data.length == 0){

                    resolve();
                    return
                }

                if(json){

                    resolve(json[key]);
                    return;
                }

                json = JSON.parse( data.toString());
                resolve(json[key]);
            })
        })
    },
    set(key ,val){

        return new Promise((resolve, reject) => {

            if(!json){
                json = {};
            }
            json[key] = val;
            updJson();
            resolve();

        })
    }
};



let updJson = (function () {


    let upd = false;
    let transferStr;

    return function(){

        if(upd){

            return;
        }
        upd = true;
        transferStr =  JSON.stringify(json);
        fs.writeFile(dir, JSON.stringify(json), 'utf8', (res) => {

            upd = false;
            if(transferStr != JSON.stringify(json)){
                updJson()
            }
        });
    }
})();


export {ConstJsonManager};
